//
//  WBMainViewController.swift
//  新浪微博
//
//  Created by 名品导购网MPLife.com on 2017/11/20.
//  Copyright © 2017年 sweet. All rights reserved.
//

import UIKit
import SVProgressHUD
//定时器

private var timer: Timer?



class WBMainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupChildControllers()
        setupComposeButton()
//        setUpTimer()
        setUpNewFeatureViews()
        
        //设置代理
        delegate = self
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
    }
    
    deinit {
        //销毁Timer
        timer?.invalidate()
        NotificationCenter.default.removeObserver(self)
    }
    /*
     portrait 竖屏 肖像
     landspace 横屏 风景画
     使用代码控制设备的方向，可以在需要横屏的时候，单独处理
     设置支持的方向之后，当前的控制器及子控制器都会遵守这个方向
     如果播放视频 同程是通过modal展现的
 */
    
    func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
        return .portrait
    }
    //监听方法
    @objc private func userLogin(n:Notification){
//        print("用户登录通知\(n)")
        //展现登录控制器
        //通常展现控制器会和uinavigationController连用，方便返回、
        //判断notification 如果有值提示用户，重新登录
        var  when = DispatchTime .now()
        if n.object != nil {
            //设置提示样式
            SVProgressHUD .setDefaultMaskType(.gradient)
            SVProgressHUD .show(withStatus: "用户登录已经超时，请重新登录")
            //修改延迟时间
            when = DispatchTime .now() + 2
        }
        //dispatch 进行延时操作
        DispatchQueue .main .asyncAfter(deadline: when) {
            //回复提示样式
            SVProgressHUD .setDefaultMaskType(.clear)
            let vc = WBOAuthViewController()
            let nav = UINavigationController(rootViewController: vc)
           self.present(nav, animated: true, completion: nil)
        }
    }
    
    //按钮的监听方法
    //private保证方法私有，仅在当前对象被访问
    //@objc允许这个函数在运行时，通过OC的消息机制，被调用
    @objc private func composseStatus() -> () {
        //判断是否登录
        //实例化视图
        let v = WBComposeTypeView()
        
        
        //显示视图 注意闭包的循环引用
        v.show { [weak v](clsName) in
            print(clsName ?? "")
            guard let clsName = clsName,let cls = NSClassFromString(Bundle.main.namespace() + "." + clsName) as? UIViewController.Type else{
                v?.removeFromSuperview()
                return
            }
            let vc = cls.init()
            let nav = UINavigationController(rootViewController: vc)
            //让导航控制器强行更新约束
            //如果发现不希望的布局约束和动画混在一起，应该向前寻找 强行更新约束
            nav.view.layoutIfNeeded()
            self.present(nav, animated: true){
                v?.removeFromSuperview()
            }
        }
    }
    
    //撰写按钮
    private lazy var composeButton:UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
}
extension WBMainViewController:UITabBarControllerDelegate{
    
    
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        print("将要切换到\(viewController)")
        //获取控制器在数组中的索引
        let idx = (childViewControllers as NSArray).index(of: viewController)
        //判断当前索引是首页 同时idx也是首页，重复点击首页按钮

        if selectedIndex == 0 && idx == selectedIndex{
//            print("点击首页")
            //让表格滚动到顶部
           //获取到控制器
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav .childViewControllers[0] as! WBHomeViewController
            //滚动到顶部
            vc .tableView?.setContentOffset(CGPoint(x:0,y:-64), animated: true)
            //刷新表格
            DispatchQueue.main .asyncAfter(deadline: DispatchTime .now(), execute: {
                vc .loadData()//加一个延迟会更好的设置congtentOffSet
            })
            //清除消息数目
            vc.tabBarItem.badgeValue = nil
            UIApplication .shared.applicationIconBadgeNumber = 0
        }
        //判断目标控制器是否是UIViewController
        return !viewController .isMember(of: UIViewController.self)
    }
 
}


//时钟相关方法
extension WBMainViewController{
    private func setUpTimer(){
        //时间间隔建议长一些，
        timer = Timer .scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    //时钟出发出发方法
    @objc private func updateTimer(){
        //如果没有登录直接return
        if !WBNetworkManager .shared .userLogon{
            return
        }
        
        WBNetworkManager .shared .unreadCount { (count) in
            //设置app tabbar  bageNumber
            //闭包里面用self
            print("检测到\(count)条新微博")
            self.tabBar .items?[0] .badgeValue = count > 0 ? "\(count)" : nil
            //设置app的bageNumber
            //从ios8.0开始，要用户授权之后才能显示
            UIApplication .shared .applicationIconBadgeNumber = count
        }
    }
}


//类似于OC中的Category 在Swift中可以用来切分代码块
//可以吧相近功能的函数，放在一个exstension中
//便于代码维护
//注意和OC的分类一样，extension中不能定义属性

extension WBMainViewController{
    //设置所有子控制器
    
    private func setupComposeButton(){
        tabBar .addSubview(composeButton)
        let count = CGFloat(childViewControllers.count)
        //将向内缩进的宽度减少，能让按钮的宽度变大 盖住容错点 防止穿帮
//        let w = tabBar.bounds.width / count-1
        let w = tabBar.bounds.width / count

        //CGRectInsert 正数向内缩进 负数，向外扩展
        //通过调整dy的值 来调整是否按钮超出tabbar
        composeButton.frame = tabBar.bounds.insetBy(dx: 2*w, dy: 0)
        print("按钮宽度\(composeButton.bounds.width)")
        composeButton .addTarget(self, action: #selector(composseStatus), for: .touchUpInside)
        
    }
    
    private func setupChildControllers(){
        
        //获取沙盒json路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString) .appendingPathComponent("main.json")
        var data = NSData(contentsOfFile: jsonPath)
        if data == nil {
            let path = Bundle .main .path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        //从bundle 加载配置的json
        //路径
        //加载NSData
        //反序列换转换成数组
        guard let  array = try? JSONSerialization .jsonObject(with: data! as Data, options: []) as? [[String:AnyObject]]
        else {
            return
        }
        
        
        
        //在现在的很多应用程序中，都依赖网络的json
        /*let array:[[String: AnyObject]] = [
            ["clsName":"WBHomeViewController" as AnyObject,"title":"首页" as AnyObject ,"imageName":"home" as AnyObject,"visitorInfo":["imageName":"","message":"关注一些人,回这里看看有什么惊喜"] as AnyObject
            ],
            ["clsName":"WBMessageViewController" as AnyObject,"title":"消息" as AnyObject,"imageName":"message_center" as AnyObject,"visitorInfo":["imageName":"visitordiscover_image_message","message":"登录后，别人评论你的微博，发给你的消息，都会在这里收到通知"] as AnyObject],
            ["clsName":"UIViewController" as AnyObject],
            ["clsName":"WBDiscoverViewController" as AnyObject,"title":"发现" as AnyObject,"imageName":"discover" as AnyObject,"visitorInfo":["imageName":"visitordiscover_image_message","message":"登录后，最新，最热微博尽在掌握，不坏在于实事潮流擦肩而过"] as AnyObject],
            ["clsName":"WBProfileViewController" as AnyObject,"title":"我的" as AnyObject,"imageName":"profile" as AnyObject,"visitorInfo":["imageName":"visitordiscover_image_profile","message":"登录后，你的微博,相册,个人资料会显示在这里，展示给别人"] as AnyObject]
        ]
        //测试数据格式是否正确 转换成plist数据更加直观
//        (array as NSArray).write(toFile: "/Users/mplife/Desktop/demo.plist", atomically: true)//保存到plist
        //数组转化成json
        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
        (data as NSData) .write(toFile: "/Users/mplife/Desktop/demo.json", atomically: true)*/
        //遍历数组，循环创建控制器数组
        var arrayM = [UIViewController]()
        for dict in array! {
            arrayM.append(controller(dict: dict))
        }
        //设置tabbar的子控制器
        viewControllers = arrayM
    }
    private func controller(dict: [String: AnyObject]) ->UIViewController{
        //取得字典内容
        guard let clsName = dict["clsName"] as? String ,
            let titl = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.namespace() + "." + clsName) as? WBBaseViewController.Type,let visitorDict = dict["visitorInfo"] as? [String:String]
            else {
            return UIViewController()
        }
        //创建视图控制器
        let vc = cls.init()
        vc.title = titl
        vc.visitorInfoDictionary = visitorDict//访客视图字典赋值
        vc.tabBarItem.image = UIImage(named: "tabbar_"+imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        //设置tabbar的标题字体
//  vc.tabBarItem .setTitleTextAttributes([NSAttributedStringKey.foregroundColor:UIColor.orange], for: .highlighted)
        vc.tabBarItem .setTitleTextAttributes([NSAttributedStringKey.foregroundColor:UIColor.orange], for: .selected)

        
        //系统默认是12号字体修改字体大小 要设置Normal的字体大小 设置高亮状态的字体大小是没有作用的
   vc.tabBarItem .setTitleTextAttributes([NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12)], for: .normal)
        let nav = WBNavigationController(rootViewController: vc)
        return nav
    }
}
//新特性是视图处理
extension WBMainViewController{
    
    private func setUpNewFeatureViews(){
        //判断是否登录
        if !WBNetworkManager .shared .userLogon {
            return
        }
        
        /*
         1.检查版本是否更新
         2.如果更新，显示新特性 否则显示欢迎
         3.添加视图
 */
        //计算型属性 不是一个单纯的变量，不会占用存储空间，类似于一个函数 给属性分配空间
        /*
         版本号
         在App Store每次发布，升级应用程序 版本号都要增加
       组成  主版本号 .此版本号.修订版本号
         主版本号变化，意味着打的修改  使用者也需要做大的适应
         此版本号 修改不大 某些函数和方法有变化
         修订版本号 框架内部bug的修订，对使用者影响不大
 */
        var isNewVersion:Bool{
            //1.取当前的版本号
//            CFBundleShortVersionString
//            print("版本信息\(String(describing: Bundle.main.infoDictionary))")
            let currentvVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
            print(currentvVersion)
            
            //2.保存在document目录中之前的版本号 版本号最好保存在用户偏好设置中
            let path:String = ("version" as NSString).cz_appendDocumentDir()
            let sandBoxVersion  = (try? String(contentsOfFile: path)) ?? ""
//            print(sandBoxVersion)
//            print(path)
            
            
            //3.将当前的版本号保存在沙盒中
            _ = try? currentvVersion .write(toFile: path, atomically: true, encoding: .utf8)
            //4.返回两个版本号的比较结果，是否一致 不一致是新版本
            if currentvVersion != sandBoxVersion {
                return true
            }else{
                return false
            }
        }
        let v = isNewVersion ? WBNewFeature(frame: view.bounds) : WBWelcomeView(frame: view .bounds)
//        let v = WBNewFeature(frame: view .bounds)
        view .addSubview(v)
    }
}


















